package com.example.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.project.common.ex.BusinessException;
import com.example.project.dao.UserDAO;
import com.example.project.dto.vo.UserLoginVO;
import com.example.project.entity.User;
import com.example.project.entity.Role;
import com.example.project.entity.AdminUserRole;
import com.example.project.mapper.UserMapper;
import com.example.project.mapper.RoleMapper;
import com.example.project.mapper.AdminUserRoleMapper;

import com.example.project.service.UserService;

import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.example.project.dto.form.UserLoginForm;
import com.example.project.dto.form.UserCreateForm;
import java.time.LocalDateTime;


@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    @Override
    public void updateUserPassword(User user) {
        userMapper.updateById(user);
    }
    @Override
    public User getUserEntityById(Long id) {
        return userMapper.selectById(id);
    }
    @Override
    public UserLoginVO getCurrentUserInfo() {
        // 获取当前登录用户信息（session方式）
        // 需要在 Controller 层通过 HttpServletRequest 传递 session
        // 这里用 RequestContextHolder 获取当前 request
    jakarta.servlet.http.HttpServletRequest request = ((org.springframework.web.context.request.ServletRequestAttributes)
        org.springframework.web.context.request.RequestContextHolder.getRequestAttributes()).getRequest();
        Object userObj = request.getSession().getAttribute("user");
        if (userObj == null || !(userObj instanceof User)) {
            throw new BusinessException("未登录或会话已过期");
        }
        User user = (User) userObj;
        UserLoginVO vo = new UserLoginVO();
        vo.setUserId(user.getId());
        vo.setUsername(user.getUserName());
        vo.setAvatar(user.getAvatar());
        vo.setEmail(user.getEmail());
        vo.setPhone(user.getPhone());
        vo.setSchool(user.getSchool());
        vo.setGender(user.getGender());
        vo.setBirthday(user.getBirthday());
        return vo;
    }
    @Override
    public void updateUserInfo(com.example.project.dto.form.UserInfoForm form) {
        User user = userMapper.selectById(form.getId());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        // 更新字段
        if (form.getAvatar() != null) user.setAvatar(form.getAvatar());
        if (form.getEmail() != null) user.setEmail(form.getEmail());
        if (form.getPhone() != null) user.setPhone(form.getPhone());
        if (form.getSchool() != null) user.setSchool(form.getSchool());
        if (form.getGender() != null) user.setGender(form.getGender());
        if (form.getBirthday() != null) user.setBirthday(form.getBirthday());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
    }
    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final AdminUserRoleMapper adminUserRoleMapper;

    @Override
    public UserLoginVO login(UserLoginForm form) {
        // 1. 根据用户名查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, form.getUsername()));

        // 2. 用户不存在或密码错误
        if (user == null || !form.getPassword().equals(user.getPassword())) {
            throw new BusinessException(400, "用户名或密码错误");
        }

        System.out.println(user.getId());
        // 4. 返回登录结果
    UserLoginVO vo = new UserLoginVO();
    vo.setUserId(user.getId());
    vo.setUsername(user.getUserName());
    vo.setAvatar(user.getAvatar());
    vo.setEmail(user.getEmail());
    vo.setPhone(user.getPhone());
    vo.setSchool(user.getSchool());
    vo.setGender(user.getGender());
    vo.setBirthday(user.getBirthday());
    System.out.println(vo);
    return vo;
    }

    @Override
    public void register(UserCreateForm form) {
        // 检查用户名是否已存在
        User existed = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, form.getUsername()));
        if (existed != null) {
            throw new BusinessException("用户名已存在");
        }
        // 直接保存明文密码，忽略 salt
        User user = new User();
        user.setUserName(form.getUsername());
        user.setPassword(form.getPassword());
        user.setEmail(form.getEmail());
        // 默认头像
        user.setAvatar("https://s1.ax1x.com/2020/09/10/wGlRa9.png");
        // 默认状态
        user.setState(1);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setLoginIp("0:0:0:0:0:0:0:1");
        user.setRegIp("0:0:0:0:0:0:0:0");
        user.setSalt("");
        userMapper.insert(user);

        // 绑定默认角色：普通用户 generalUser（若未配置则回退到 rid=3）
        Role generalRole = roleMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getName, "generalUser"));
        Integer rid = generalRole != null ? generalRole.getId() : 3;
        AdminUserRole aur = new AdminUserRole();
        aur.setUid(user.getId().intValue());
        aur.setRid(rid);
        adminUserRoleMapper.insert(aur);
    }

}
